<template>
    <div class="flex_col card2 m5 p10">
        <div class="flex_row_center">
            <label>串口名:</label>
            <el-select style="width: 120px;" v-model="ctx.selectName">
                <el-option v-for="(item, index) in ctx.portNames" :key="index" :label="item" :value="item"/>
            </el-select>
            <el-button type="warning" @click="init" class="ml5">刷新串口</el-button>
        </div>
        <div class="flex_row_center mt5">
            <label>波特率:</label>
            <el-input v-model="ctx.baudRate" clearable style="width: 120px;"/>
        </div>
        <div class="flex_row mt5" style="justify-content: center;">
            <el-button type="primary" @click="onClickOpen">{{ ctx.btnText }}</el-button>
        </div>
    </div>
</template>

<script setup lang="ts">

import { reactive } from 'vue';
import { serialPort } from '../service/conn';
import { run } from '../utils/ui';

interface Ctx {
    portNames: string[],
    selectName: string,
    baudRate: string,
    btnText: string,
}

const ctx = reactive<Ctx>({
    portNames: [],
    selectName: '',
    baudRate: '9600',
    btnText: '打开',
})

async function updateState() {
    if (await serialPort.isOpen()) {
        ctx.btnText = '关闭';
    } else {
        ctx.btnText = '打开';
    }
}

async function init() {
    const ports = await serialPort.getCurrentPortNames();
    ctx.portNames = ports;
    if (ports.length != 0) {
        ctx.selectName = ports[0];
    }
}

async function onClickOpen() {
    run(async () => {
        if (await serialPort.isOpen()) {
            await serialPort.close();
            await updateState();
            return;
        }
        if (ctx.selectName.length == 0) {
            throw '串口没有选择';
        }
        if (ctx.baudRate.length == 0) {
            throw '请输入波特率';
        }
        const baudRate = parseInt(ctx.baudRate);
        await serialPort.open(ctx.selectName, baudRate);
        await updateState();
    });
}

init();
updateState();

</script>
